package hgin

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"reflect"
	"vitepress-serve/internal/common/errs"
)

func Must[T any](v T, err error) T {
	if err != nil {
		panic(err)
	}
	return v
}

// Bind 绑定Body参数到结构体
func Bind[T any](ctx *gin.Context) (v T) {
	err := ctx.ShouldBindJSON(&v)
	if err != nil {
		panic(errs.E99901.SetMessage(GetValidMsg(err, v)))
	}
	return
}

// GetValidMsg 根据gin参数验证器返回对应结构体的错误msg tag
func GetValidMsg(err error, obj interface{}) string {
	getObj := reflect.TypeOf(obj)
	if errss, ok := err.(validator.ValidationErrors); ok {
		for _, e := range errss {
			if f, exist := getObj.Elem().FieldByName(e.Field()); exist {
				return f.Tag.Get("msg")
			}
		}
	}
	return err.Error()
}
